﻿using Core.Factory;
using EntityFramework;
using Model;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Core.Service
{
    public class JoinService : IJoinService
    {
        private readonly Logger Logger = LogManager.GetCurrentClassLogger();
        private readonly IActivityService _activityService;
        private readonly MyDbContext _myDbContext;
        public JoinService(MyDbContext myDbContext, IActivityService activityService)
        {
            _myDbContext = myDbContext;
            _activityService = activityService;
        }

        public void SetAddress(int userId, int activityId, string address)
        {
            var model = _myDbContext.T_Join.SingleOrDefault(i => i.UserId == userId && i.ActivityId == activityId);
            model.Address = address;
            _myDbContext.SaveChanges();
        }

        public void UpdateJoins(List<T_Join> joins)
        {
            _myDbContext.Database.BeginTransaction();

            _myDbContext.T_Join.UpdateRange(joins);
            _myDbContext.SaveChanges();

            var unLuckys = _myDbContext.T_Join.Where(i => i.ActivityId == joins[0].ActivityId && i.IsLucky == 0).Select(i => i);
            foreach (var item in unLuckys)
            {
                item.ExchangeCode = null;

            }
            _myDbContext.SaveChanges();
            _myDbContext.Database.CommitTransaction();
        }

        
        public T_Join UseExchangeCode(string code)
        {
            var model=  _myDbContext.T_Join.FirstOrDefault(i=>i.ExchangeCode==code);
            if(model != null){
                model.IsExchange = 1;
                model.ExchangeTime = DateTime.Now;
            }
            _myDbContext.SaveChanges();
            return model;
        }
    }
}
